<template>
  <WithDialog
    :visible.sync="dialogVisible"
    title="编辑用车申请"
    :close-on-click-modal="false"
    @confirm="handleConfirm"
    @cancel="handleCancel"
  >
    <el-form
      ref="form"
      v-loading="loading"
      :model="formData"
      label-width="auto"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="申请人" prop="user_name">
        <el-input v-model="formData.user_name" disabled />
      </el-form-item>
      <el-form-item label="用车时间" prop="vehicle_usage_time">
        <el-date-picker
          v-model="formData.vehicle_usage_time"
          type="datetime"
          placeholder="选择用车时间"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="{
            disabledDate: time => time.getTime() < Date.now() - 8.64e7
          }"
        />
      </el-form-item>
      <el-form-item label="车辆选择" prop="vehicle_resources_id">
        <el-select v-model="formData.vehicle_resources_id" placeholder="请选择车辆">
          <el-option
            v-for="item in vehiclesList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item v-if="!isNoDriverVehicle" label="驾驶员类型" prop="driver_type">
        <el-select
          v-model="formData.driver_type"
          placeholder="请选择驾驶员类型"
          @change="handleDriverTypeChange"
        >
          <el-option
            v-for="item in driverType"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item
        v-if="!isNoDriverVehicle && formData.driver_type !== 'self'"
        label="司机选择"
        prop="driver_resources_id"
      >
        <el-select v-model="formData.driver_resources_id" placeholder="请选择司机">
          <el-option
            v-for="item in driverListFormat"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="用车事由" prop="car_reason">
        <el-input v-model="formData.car_reason" placeholder="请输入用车事由" />
      </el-form-item>

      <el-form-item label="用车路线" prop="vehicle_route">
        <el-input v-model="formData.vehicle_route" type="textarea" placeholder="请输入用车路线" />
      </el-form-item>

      <el-form-item label="是否有客户信息">
        <el-radio-group v-model="has_customer">
          <el-radio :label="true">有</el-radio>
          <el-radio :label="false">无</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-row v-if="has_customer" :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户姓名" prop="customer_name">
            <el-input v-model="formData.customer_name" placeholder="请输入客户姓名" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户电话" prop="customer_phone">
            <el-input v-model="formData.customer_phone" placeholder="请输入客户电话" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注信息" />
      </el-form-item>
    </el-form>
  </WithDialog>
</template>

<script>
import WithDialog from '@/components/WithDialog/withDialog'
import { getDriverList, getVehiclesList } from '@/api/vehicleService'
import { getAllUser } from '@/api/v2/personnel'
import dayjs from 'dayjs'

export default {
  name: 'EditCarUse',
  components: {
    WithDialog
  },
  props: {
    value: {
      type: Object,
      default: () => ({})
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {

      },
      has_customer: false,
      vehiclesList: [],
      driverType: [
        {
          label: '司机',
          value: 'driver'
        },
        {
          label: '本人',
          value: 'self'
        },
        {
          label: '非本人',
          value: 'notSelf'
        }
      ],
      driverList: [],
      userList: [],
      rules: {
        vehicle_usage_time: [
          { required: true, message: '请选择用车时间', trigger: 'change' },
          { validator: (rule, value, callback) => {
            if (dayjs(value).isBefore(dayjs())) {
              console.log(value)
              callback(new Error('用车时间必须在当前时间之后'))
            } else {
              callback()
            }
          }, trigger: 'change' }
        ],
        vehicle_resources_id: [{ required: true, message: '请选择车辆', trigger: 'change' }],
        driver_type: [{ required: true, message: '请选择驾驶员类型', trigger: 'change' }],
        driver_resources_id: [{ required: true, message: '请选择司机', trigger: 'change' }],
        car_reason: [{ required: true, message: '请输入用车事由', trigger: 'blur' }],
        vehicle_route: [{ required: true, message: '请输入用车路线', trigger: 'blur' }],
        customer_name: [{ required: true, message: '请输入客户姓名', trigger: 'blur' }],
        customer_phone: [{ required: true, message: '请输入客户电话', trigger: 'blur' }]
      },
      loading: false
    }
  },
  computed: {
    dialogVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('update:visible', val)
      }
    },
    isNoDriverVehicle() {
      const selectedVehicle = this.vehiclesList.find(item => item.value === this.formData.vehicle_resources_id)
      return selectedVehicle?.type?.type === 'noDriver'
    },
    driverListFormat() {
      if (this.formData.driver_type === 'self') {
        return []
      }
      return this.formData.driver_type === 'notSelf' ? this.userList : this.driverList
    }
  },
  watch: {
    value: {
      handler(val) {
        console.log(val, '123123123')
        this.formData = { ...val }
        console.log(this.formData.customer_name)
        if (this.formData.customer_name && this.formData.customer_phone) {
          this.has_customer = true
        }
      },
      immediate: true
    },
    'formData.vehicle_resources_id': {
      handler(val) {
        if (this.isNoDriverVehicle) {
          this.formData.driver_type = null
          this.formData.driver_resources_id = null
        }
      },
      immediate: true
    },
    'has_customer': {
      handler(val) {
        if (!val) {
          this.formData.customer_name = null
          this.formData.customer_phone = null
        }
      }
    },
    dialogVisible(val) {
      if (val) {
        this.init()
      }
    }
  },
  methods: {
    handleConfirm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (this.formData.driver_type === 'notSelf') {
            this.formData.drive_user_id = this.formData.driver_resources_id
            delete this.formData.driver_resources_id
          }
          delete this.formData.user_name
          console.log('this.formData --------->', this.formData)
          this.$emit('confirm', this.formData)
        }
      })
    },
    handleCancel() {
      this.$emit('update:visible', false)
    },
    resetFields() {
      this.$refs.form?.resetFields?.()
    },

    async init() {
      this.loading = true

      await Promise.allSettled([
        this.getVehiclesList(),
        this.getDriverList(),
        this.getUsers()
      ])

      this.loading = false
    },

    async getVehiclesList() {
      try {
        const res = await getVehiclesList({ is_available: 1 })
        console.log('res --------->', res)
        this.vehiclesList = res.data.map(item => {
          return {
            label: item?.license_plate_number
              ? `${item?.type?.name}-${item?.license_plate_number}` : `${item?.type?.name}`,
            value: item?.id,
            extra: item?.examine,
            type: item?.type
          }
        })
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      }
    },

    async getDriverList() {
      try {
        const res = await getDriverList()
        this.driverList = res.data.map(item => {
          return {
            label: item.user.username,
            value: item.id,
            userId: item?.user?.id
          }
        })
      } catch (error) {
        this.$message.error(error?.response?.data?.message || '信息获取失败')
      }
    },

    async getUsers() {
      try {
        const res = await getAllUser({ type: 2 })
        this.userList = res.data.map(item => {
          return {
            value: item.id,
            label: item.username,
            userId: item.id
          }
        })
      } catch (e) {
        throw new Error(e?.response?.data?.message || '用户列表获取失败')
      }
    },

    handleDriverTypeChange() {
      this.formData.driver_resources_id = null
      this.$nextTick(() => {
        this.$refs?.form?.clearValidate('driver_resources_id')
      })
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
